import org.omg.PortableInterceptor.INACTIVE;

import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/12 22:18
 * @description 幷查集 + 因子分解
 */
public class Solution {
    public static void main(String[] args) {
        int[] nums = {2,3,6,7,4,12,21,39};
        Solution solution = new Solution();
        solution.largestComponentSize(nums);
    }
    public int largestComponentSize(int[] A) {
        int maxVal = 0;
        for (int num : A) {
            maxVal = Math.max(maxVal, num);
        }

        // 0 位置不使用，因此需要 + 1
        UnionFind unionFind = new UnionFind(maxVal + 1);

        for (int num : A) {
            for (int i = 2; i * i <= num; i++) {
                if (num % i == 0) {
                    unionFind.union(num, i);
                    unionFind.union(num, num / i);
                }
            }
        }

        // 将候选数组映射成代表元，统计代表元出现的次数，找出最大者
        int[] cnt = new int[maxVal + 1];
        int res = 0;
        for (int num : A) {
            int root = unionFind.find(num);
            cnt[root]++;
            res = Math.max(res, cnt[root]);
        }
        return res;
    }

    private class UnionFind {
        int[] parent;

        UnionFind(int n) {
            parent = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }
        public int find(int x) {
            if (x != parent[x]) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }
        public void union(int x, int y) {
            parent[find(x)] = find(y);
        }
    }
}
